package com.creditease.mobile.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class FileUtil {
	private final static String TAG = FileUtil.class.getName();

	/**
	 * 加载本地图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getLoacalBitmap(String url) {
		try {
			FileInputStream fis = new FileInputStream(url);
			return BitmapFactory.decodeStream(fis);
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 加载本地图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getLoacalBitmap(Context ctx, String url) {
		try {
			InputStream isInputStream = ctx.getAssets().open(url);
			return BitmapFactory.decodeStream(isInputStream);
		}
		catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 从服务器取图片 http://bbs.3gstdy.com
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap getHttpBitmap(String url) {
		URL myFileUrl = null;
		Bitmap bitmap = null;
		try {
			Log.d(TAG, url);
			myFileUrl = new URL(url);
		}
		catch (MalformedURLException e) {
			e.printStackTrace();
		}
		try {
			HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
			conn.setConnectTimeout(0);
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			is.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return bitmap;
	}

	/**
	 * 通过URL获取md5文件名，不带路径
	 * description
	 * @param url
	 * @return
	 */
	public static String getFileName(String url) {
		/*String fileName = url.substring(url.lastIndexOf("/"));
		// 后缀
		String suffix=".jpg";
		if(fileName.indexOf(".")!=-1){
			suffix= fileName.substring(fileName.lastIndexOf("."));
		}
		return MD5.encodeMD5String(url) + suffix;*/
		return MD5.encodeMD5String(url) ;
	}
}
